<template>
  <div class="user-manage-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchKey"
        placeholder="请输入用户名"
        clearable
        @clear="loadUserData"
        @keyup.enter="loadUserData"
      >
        <template #append>
          <el-button :icon="Search" @click="loadUserData" />
        </template>
      </el-input>
      <el-button type="primary" @click="exportToExcel">
          <el-icon><Download /></el-icon>
          导出Excel
        </el-button>
        <el-upload
          action=""
          :show-file-list="false"
          :before-upload="beforeExcelUpload"
          :http-request="importFromExcel"
          accept=".xlsx, .xls"
          style="display: inline-block; margin-left: 10px;"
        >
          <el-button type="warning">
            <el-icon><Upload /></el-icon>
            导入Excel
          </el-button>
        </el-upload>
    </div>

    <!-- 用户表格 -->
    <el-table :data="userList" border stripe style="width: 100%"
    @sort-change="handleSortChange" 
    remote-sort
    >
      <el-table-column 
      prop="id" 
      label="ID"
      width="80" 
      align="center" 
      sortable 
      :sort-orders="['ascending', 'descending']"/>
      <el-table-column prop="username" label="用户名" width="150" />
      <el-table-column prop="fullName" label="真实姓名" width="120" />
      <el-table-column prop="gender" label="性别" width="80" align="center">
        <template #default="{ row }">
          {{ row.gender || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号" width="150" />
      <el-table-column prop="role" label="角色" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.role === 'ADMIN' ? 'danger' : 'success'">
            {{ row.role === 'ADMIN' ? '管理员' : '普通用户' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="addTime" label="注册时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.addTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="profileImage" label="头像" width="120" align="center">
        <template #default="{ row }">
          <el-avatar :size="40" :src="row.profileImage" />
        </template>
      </el-table-column>
       <el-table-column label="操作" width="120" align="center">
        <template #default="{ row }">
          <el-button
            type="danger"
            size="small"
            @click="handleDeleteUser(row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
      
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[5, 10, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="loadUserData"
        @current-change="loadUserData"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus';
// 数据定义
const userList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchKey = ref('')
const sortProp = ref('id')    // 默认排序字段
const sortOrder = ref('asc')  // 默认排序方向
const token = localStorage.getItem('token');
// 加载用户数据
const loadUserData = async () => {
  try {
    const { data } = await axios.get('/user/page', {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value,
        username: searchKey.value,
        sortField: sortProp.value,   // 新增排序字段参数
        sortOrder: sortOrder.value   // 新增排序方向参数
      }
    });
    
    // 根据实际响应字段名调整（假设后端返回的字段是 data）
    userList.value = data.data;  // 修改此处
    total.value = data.total;
  } catch (error) {
    console.error('加载用户数据失败:', error);
  }
};
// 处理排序变化
const handleSortChange = ({ prop, order }: { prop: string; order: 'ascending' | 'descending' | null }) => {
  sortProp.value = prop
  sortOrder.value = order === 'ascending' ? 'asc' : 'desc'
  loadUserData()
}
// 日期格式化
const formatDate = (date: string | Date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString()
}
const handleDeleteUser = async (userId: number) => {
  try {
    await ElMessageBox.confirm('确定要删除该用户吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    const response = await axios.delete(`/user/delete/${userId}`,{
         headers: {
        Authorization: `Bearer ${token}`  // 在请求头中添加 Token
      }
    });
    if (response.data === 'User deleted successfully') {
      ElMessage.success('删除成功');
      loadUserData();
    }
  } catch (error: any) { // 明确指定 error 类型
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + (error.response?.data || error.message));
    }
  }
};
const exportToExcel = async () => {
  try {
    const token = localStorage.getItem('token');
    const response = await axios.get('/user/export', {
      responseType: 'blob',
      params: {  // 添加查询参数
        username: searchKey.value,
        sortField: sortProp.value,
        sortOrder: sortOrder.value
      },
      headers: { Authorization: `Bearer ${token}` }
    });
    
    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', '用户数据.xlsx');
    document.body.appendChild(link);
    link.click();
    
    // 清理
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    
    ElMessage.success('导出成功');
  } catch (error) {
    ElMessage.error('导出失败: ' + (error as Error).message);
  }
};
// 导入Excel前的文件类型检查
const beforeExcelUpload = (file: File) => {
  const isExcel = /\.(xlsx|xls)$/.test(file.name.toLowerCase());
  if (!isExcel) {
    ElMessage.error('只能上传Excel文件!');
    return false;
  }
  return true;
};

// 导入Excel
const importFromExcel = async (options: any) => {
  try {
    const token = localStorage.getItem('token');
    const formData = new FormData();
    formData.append('file', options.file);
    
    const response = await axios.post('/user/import', formData, {
      headers: { 
        'Content-Type': 'multipart/form-data',
        Authorization: `Bearer ${token}` 
      }
    });
    
    // 处理响应数据
    if (response.data.status === 'success') {
      ElMessage.success(response.data.message);
      loadUserData(); // 重新加载数据
    } else {
      ElMessage.error(response.data.message || '导入失败');
    }
  } catch (error: any) {
    let errorMessage = '导入失败';
    if (error.response && error.response.data && error.response.data.message) {
      errorMessage += ': ' + error.response.data.message;
    } else if (error.message) {
      errorMessage += ': ' + error.message;
    }
    ElMessage.error(errorMessage);
  }
};

// 初始化加载
onMounted(() => {
  loadUserData()
})
</script>

<style scoped>
.user-manage-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
}

.search-bar {
  margin-bottom: 20px;
  width: 300px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}


</style>